import time
import chardet
import random
import string
from flask_restful import Resource, reqparse
import base64
import subprocess
from huiyan.extions import cache


# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('base64_doc_data', type=str, required=True, help='base64_doc_data is required.')

# 读取doc格式的文件
class doc(Resource):
    def post(self):
        args = parser.parse_args()
        base64_doc_data: str = args.get('base64_doc_data')

        try:
            # 将 base64 编码的字符串解码成二进制数据
            binary_data = base64.b64decode(base64_doc_data)

            # 生成一个包含指定长度随机字符的字符串
            random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) + str(
                int(time.time()))

            # 将二进制数据写入一个临时文件
            temp_file_path = f'/tmp/{random_string}.doc'
            with open(temp_file_path, 'wb') as f:
                f.write(binary_data)

            # 调用 antiword 工具读取临时文件内容
            result = subprocess.run(['antiword', temp_file_path], stdout=subprocess.PIPE)
            # text = result.stdout.decode('utf-8')
            encoding = chardet.detect(result.stdout)['encoding']
            text = result.stdout.decode(encoding)

            # 删除临时文件
            subprocess.run(['rm', temp_file_path])

            # cache.set(Req.url, data_, timeout=60 * 60 * 24)
            return {
                "data": text,
                "status": 200,
                "msg": None
            }
        except:
            return {
                "status": 400,
                "msg": '服务器请求错误,请重试'
            }


